package com.cqemme.messageservice.component;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cqemme.messageservice.util.EmptyChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
@Slf4j
public class SendSms {

    @Value("${note.accessKeyId}")
    private String accessKeyId;

    @Value("${note.accessSecret}")
    private String accessSecret;

    public void send(Map<String, Object> json) throws ClientException {

        Object par = json.get("par");
        String mobile = json.get("mobile")+"";
        String outId = json.get("outId")+"";
        String siginName = json.get("siginName")+"";
        String templateCode = json.get("templateCode")+"";

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", siginName);
        request.putQueryParameter("TemplateCode", templateCode);
        if (EmptyChecker.notEmpty(par)) {
            request.putQueryParameter("TemplateParam", JSONObject.toJSONString(par));
        }
        if (EmptyChecker.notEmpty(outId)) {
            request.putQueryParameter("OutId", outId);
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
            log.error("短信发送失败",e);
        } catch (ClientException e) {
            e.printStackTrace();
            log.error("短信发送失败",e);
        }
    }

}